package com.songxh.domain.service.report;

import com.songxh.domain.service.api.ArticleService;
import com.songxh.infrastructure.db.pojo.Article;
import com.songxh.shared.config.ThreadPoolConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * @author songxh
 * @create 2023-01-10-14:26
 */
@Component
@Slf4j
public class ReportUtils {

    /**
     * 异步修改浏览数量
     *
     * @param article
     * @param articleService
     */
    @Async(ThreadPoolConfig.VIEW_COUNT_ASYNC_NAME)
    public void handlerViewCountAsync(Article article, ArticleService articleService) {
        //先获取当前浏览数量
        Integer viewCounts = article.getViewCounts();
        articleService.lambdaUpdate()
                .eq(Article::getId, article.getId())
                .eq(Article::getViewCounts, viewCounts)  //类似CAS，校验当前的浏览数量是否与之前的一致
                .set(Article::getViewCounts, viewCounts + 1)
                .update();
        try {
            //使用sleep的目的：让出时间片，cpu立即去执行其他的线程，使cpu更容易易主
            Thread.sleep(5000);
            log.info("浏览数量更新完成！");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
